package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.adapter.HuodongAdapter;
import com.ycsj.goldmedalnewconcept.bean.AttResponse;
import com.ycsj.goldmedalnewconcept.bean.HuodongResponse;
import com.ycsj.goldmedalnewconcept.bean.HuodongResponse.Huodonglist;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.PullToRefreshLayout;
import com.ycsj.goldmedalnewconcept.R;

//活动列表
@SuppressLint("HandlerLeak")
public class HuodongActivity extends Activity implements OnRefreshListener,
		OnClickListener {
	private ListView lv_friends;
	private HuodongAdapter mAdapter;
	private ImageView iv_back;
	private TextView tv_newhuodong;
	private PullToRefreshLayout refreshLayout;
	private List<Huodonglist> list;
	private List<Huodonglist> list2;
	private String role;
	private String account;
	private String rowid;
	private int page = 0;
	private TextView loadTextView;
	private TextView tv_empty;
	private View footerView;
	private View loading;
	private boolean isLoading = false;
	private RotateAnimation loadingAnimation;
	private LinearLayout llLoading;
	
	private IntentFilter intentFilter;
	private MyBroadcastReceiver myBroadcastReceiver;
	public static final String BROADCAST_ACTION="refreshbroadcast";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_huodong);

		role = SPUtil.getString(this, "role", "");
		account = SPUtil.getString(this, "account", "");

		list = new ArrayList<Huodonglist>();
		list2 = new ArrayList<Huodonglist>();

		loadingAnimation = (RotateAnimation) AnimationUtils.loadAnimation(this,
				R.anim.rotating);
		// 添加匀速转动动画
		LinearInterpolator lir = new LinearInterpolator();
		loadingAnimation.setInterpolator(lir);

		initView();
		setOnListener();
		registerCast();
		initData();
	}

	/**
	 * 创建广播用于处理页面刷新
	 */
	private void registerCast() {
		 	intentFilter = new IntentFilter();
	        intentFilter.addAction("refreshbroadcast");
	        myBroadcastReceiver = new MyBroadcastReceiver();
	        registerReceiver(myBroadcastReceiver, intentFilter);
		
	}

	
	 /**
     * 广播接受者
     */
    public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //收到广播受重新刷新页面数据
            if (BROADCAST_ACTION.equals(intent.getAction())) {
            	onRefresh();
            	Log.e("TEST", "RUN");
            }
        }
    }
	
	
	private void initView() {
		if ("2".equals(role)) {
			tv_newhuodong = (TextView) findViewById(R.id.tv_newhuodong);
			tv_newhuodong.setVisibility(tv_newhuodong.VISIBLE);
		}

		llLoading = (LinearLayout) findViewById(R.id.ll_loading);

		lv_friends = (ListView) findViewById(R.id.lv_friends);
		iv_back = (ImageView) findViewById(R.id.iv_back);
		refreshLayout = (PullToRefreshLayout) findViewById(R.id.refresh_view);

		footerView = this.getLayoutInflater().inflate(R.layout.load_more_jpstar, null);
		loading = footerView.findViewById(R.id.loading_icon);
		loadTextView = (TextView) footerView.findViewById(R.id.loadmore_tv);
		tv_empty = (TextView) findViewById(R.id.tv_empty);
		lv_friends.addFooterView(footerView, null, false);
		footerView.setOnClickListener(this);

	}

	private void setOnListener() {
		refreshLayout.setOnRefreshListener(this);

		iv_back.setOnClickListener(this);
		if ("2".equals(role)) {
			tv_newhuodong.setOnClickListener(this);
		}
	}

	private void initData() {

		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "6");
		builder.add("c", account);
		builder.add("role", role);
		builder.add("page", page + "");
		Request request = new Request.Builder()
				.url(Constant.SERVER_LOC + "PersonalAssistantMsg")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				Gson gson = new Gson();
				String json = arg0.body().string();
				HuodongResponse fromJson = gson.fromJson(json,
						HuodongResponse.class);

				if (fromJson != null) {
					if ("-1".equals(fromJson.state)
							|| "0".equals(fromJson.state)) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								if (page == 0) {
										if(llLoading.getVisibility()!=View.GONE){
											llLoading.setVisibility(View.GONE);
										}
									tv_empty.setVisibility(tv_empty.VISIBLE);
									lv_friends.setVisibility(tv_empty.GONE);
								}

								loading.setVisibility(loading.GONE);
								loading.clearAnimation();
								loadTextView.setText("已经是最后一条了");
								loadTextView.setClickable(false);
								isLoading = true;
								page = 0;
							}
						});
					} else if ("1".equals(fromJson.state)) {
						// 解析新数据
						list2 = fromJson.list;
						if (page == 0) {
							// 正常请求或者下拉刷新
							list = list2;
						} else {
							// 加载更多
							list.addAll(list2);
						}

						runOnUiThread(new Runnable() {
							@Override
							public void run() {

								refreshLayout
										.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
								tv_empty.setVisibility(tv_empty.GONE);
								lv_friends.setVisibility(tv_empty.VISIBLE);
								mAdapter = new HuodongAdapter(
										HuodongActivity.this, list);
								if (page == 0) {
									if(list.size()!=0){
										if(llLoading.getVisibility()!=View.GONE){
											llLoading.setVisibility(View.GONE);
										}
									}
									lv_friends.setAdapter(mAdapter);
								} else {
									runOnUiThread(new Runnable() {
										@Override
										public void run() {
											mAdapter.notifyDataSetChanged();
										}
									});
								}

								lv_friends
										.setOnItemClickListener(new OnItemClickListener() {

											@Override
											public void onItemClick(
													AdapterView<?> parent,
													View view, int position,
													long id) {
												Intent intent = new Intent(
														HuodongActivity.this,
														HuodongDetailsActivity.class);
												intent.putExtra("tag",
														list.get(position).tag);
												intent.putExtra(
														"begin_date",
														list.get(position).begin_date);
												intent.putExtra(
														"end_date",
														list.get(position).end_date);
												intent.putExtra(
														"address",
														list.get(position).address);
												intent.putExtra(
														"content",
														list.get(position).content);
												intent.putExtra(
														"persons",
														list.get(position).persons);
												intent.putExtra(
														"rowid",
														list.get(position).row_id
																+ "");
												intent.putExtra(
														"start_status",
														list.get(position).start_status);
												intent.putExtra(
														"enroll_status",
														list.get(position).enroll_status);
												if (list.get(position).user_picture1 != null
														&& !"".equals(list
																.get(position).user_picture1)) {
													intent.putExtra(
															"pic1",
															list.get(position).user_picture1);
												}
												if (list.get(position).user_picture2 != null
														&& !"".equals(list
																.get(position).user_picture2)) {
													intent.putExtra(
															"pic2",
															list.get(position).user_picture2);
												}
												if (list.get(position).user_picture3 != null
														&& !"".equals(list
																.get(position).user_picture3)) {
													intent.putExtra(
															"pic3",
															list.get(position).user_picture3);
												}
												if (list.get(position).user_picture4 != null
														&& !"".equals(list
																.get(position).user_picture4)) {
													intent.putExtra(
															"pic4",
															list.get(position).user_picture4);
												}
												if (list.get(position).user_picture5 != null
														&& !"".equals(list
																.get(position).user_picture5)) {
													intent.putExtra(
															"pic5",
															list.get(position).user_picture5);
												}
												if (list.get(position).user_picture6 != null
														&& !"".equals(list
																.get(position).user_picture6)) {
													intent.putExtra(
															"pic6",
															list.get(position).user_picture6);
												}
												if (list.get(position).user_picture7 != null
														&& !"".equals(list
																.get(position).user_picture7)) {
													intent.putExtra(
															"pic7",
															list.get(position).user_picture7);
												}
												if (list.get(position).user_picture8 != null
														&& !"".equals(list
																.get(position).user_picture8)) {
													intent.putExtra(
															"pic8",
															list.get(position).user_picture8);
												}
												if (list.get(position).user_picture9 != null
														&& !"".equals(list
																.get(position).user_picture9)) {
													intent.putExtra(
															"pic9",
															list.get(position).user_picture9);
												}

												startActivity(intent);

											}
										});

								if ("2".equals(role)) {
									lv_friends
											.setOnItemLongClickListener(new OnItemLongClickListener() {

												@Override
												public boolean onItemLongClick(
														AdapterView<?> parent,
														View view,
														int position, long id) {
													rowid = list.get(position).row_id
															+ "";
													Log.e("test", rowid);
													deldialog(rowid);// 删除条目的弹窗
													return true;
												}

												private BaseAnimatorSet bas_in;
												private BaseAnimatorSet bas_out;

												public void setBasIn(
														BaseAnimatorSet bas_in) {
													this.bas_in = bas_in;
												}

												public void setBasOut(
														BaseAnimatorSet bas_out) {
													this.bas_out = bas_out;
												}

												private void deldialog(
														final String rowid) {

													final NormalDialog dialog = new NormalDialog(
															HuodongActivity.this);
													dialog.content("确定删除此活动？")
															.btnText("取消", "确认")//
															.style(NormalDialog.STYLE_TWO)//
															.titleTextSize(23)//
															.showAnim(bas_in)//
															.dismissAnim(
																	bas_out)//
															.show();
													dialog.setCanceledOnTouchOutside(false);
													dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {

														@Override
														public void onBtnLeftClick() {
															dialog.dismiss();
														}
													});
													dialog.setOnBtnRightClickL(new OnBtnRightClickL() {

														@Override
														public void onBtnRightClick() {
															// 删除条目
															dialog.dismiss();

															OkHttpClient mOkHttpClient = new OkHttpClient();
															FormEncodingBuilder builder = new FormEncodingBuilder();
															builder.add("type",
																	"7");
															builder.add(
																	"rowid",
																	rowid);
															builder.add("c",
																	account);
															builder.add("role",
																	role);
															builder.add(
																	"status",
																	"-1");

															Request request = new Request.Builder()
																	.url(Constant.SERVER_URL
																			+ "PersonalAssistantMsg")
																	.post(builder
																			.build())
																	.build();
															mOkHttpClient
																	.newCall(
																			request)
																	.enqueue(
																			new Callback() {

																				@Override
																				public void onFailure(
																						Request arg0,
																						IOException arg1) {
																					runOnUiThread(new Runnable() {
																						@Override
																						public void run() {
																							Toast.makeText(
																									getBaseContext(),
																									"网络无响应，请检查网络连接",
																									0)
																									.show();
																						}
																					});
																				}

																				@Override
																				public void onResponse(
																						Response arg0)
																						throws IOException {
																					// 解析Json数据，保存登录状态及身份信息

																					Gson gson = new Gson();
																					String json = arg0
																							.body()
																							.string();
																					Log.e("test",
																							json);
																					AttResponse fromJson = gson
																							.fromJson(
																									json,
																									AttResponse.class);

																					if (fromJson != null) {
																						if ("-1".equals(fromJson.state)
																								|| "0".equals(fromJson.state)) {
																							runOnUiThread(new Runnable() {
																								@Override
																								public void run() {
																									Toast.makeText(
																											getBaseContext(),
																											"删除失败，请检查网络连接是否正常",
																											0)
																											.show();
																								}
																							});
																						} else if ("1"
																								.equals(fromJson.state)) {

																							runOnUiThread(new Runnable() {
																								@Override
																								public void run() {
																									onRefresh();
																									Toast.makeText(
																											getBaseContext(),
																											"删除成功！",
																											0)
																											.show();

																								}
																							});
																						}
																					}
																				}
																			});

														}
													});

												}
											});
								}

								loading.setVisibility(loading.GONE);
								loading.clearAnimation();
								if (list2.size() < 5) {
									loadTextView.setText("已经是最后一条了");
									loadTextView.setClickable(false);
									isLoading = true;
									page = 0;
								} else {
									loadTextView.setText("加载更多");
									isLoading = false;
								}
							}
						});
					}
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.tv_newhuodong:
			Intent intent = new Intent(this, ClassListActivity.class);
			intent.putExtra("view_type", "7");
			intent.putExtra("user_id", account);
			startActivity(intent);
			break;
		case R.id.loadmore_layout:
			if (!isLoading) {
				loading.setVisibility(View.VISIBLE);
				loading.startAnimation(loadingAnimation);
				loadTextView.setText("正在加载...");
				isLoading = true;
				page++;
				initData();
			}
			break;
		}
	}

	
	
//	@Override
//	protected void onRestart() {
//		// TODO Auto-generated method stub
//		super.onRestart();
////		onRefresh();
//	}
	
	
	
	
	

	@Override
	public void onRefresh() {
		// 下拉刷新操作
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				page = 0;
				initData();
				loadTextView.setText("加载更多");
				loading.setVisibility(View.GONE);
				isLoading = false;

			}
		}, 500);
	}

}
